<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>

<style type="text/css">

    /*设置 layui 表格中单元格内容溢出可见样式*/
    #divtable .layui-table-view,
    #divtable .layui-table-box,
    #divtable .layui-table-body {
        overflow: visible;
    }

    #divtable .layui-table-cell {
        height: auto;
        overflow: visible;
    }

    /*文本对齐方式*/
    .text-center {
        text-align: center;
    }

    /* 使得下拉框与单元格刚好合适 */
    td .layui-form-select {
        margin-top: -5px;
        margin-left: -15px;
        margin-right: -15px;
    }

    #divtable .layui-anim-upbit {
        margin-top: -10px;
    }
</style>
<div id="yclPurchaseOrderPage" style="margin: 15px">
    <%--query tools--%>
    <blockquote class="layui-elem-quote">
        <div class="layui-fluid">
            <div class="layui-row">
                <div class="layui-col-sm3">
                    <div class="layui-inline">
                        <label style="width: 65px">订单号</label>
                        <div class="layui-input-inline">
                            <input type="text" class="layui-input" v-model="queryParams.poCode"/>
                        </div>
                    </div>
                </div>
                <div class="layui-col-sm3">
                    <div class="layui-inline">
                        <label style="width: 65px">供应商名称</label>
                        <div class="layui-input-inline">
                            <input type="text" class="layui-input" v-model="queryParams.supplierName"/>
                        </div>
                    </div>
                </div>
                <div class="layui-col-sm3">
                    <div class="layui-inline">
                        <label style="width: 65px">物料编码</label>
                        <div class="layui-input-inline">
                            <input type="text" class="layui-input" v-model="queryParams.materialCode"/>
                        </div>
                    </div>
                </div>
                <div class="layui-col-sm3">
                    <div class="layui-inline">
                        <button type="button" class="layui-btn layui-btn-sm layui-btn-normal" @click="queryPageView">
                            <i class="layui-icon">&#xe615;</i>查询
                        </button>
                    </div>
                    <div class="layui-inline">
                        <button type="button" class="layui-btn layui-btn-primary layui-btn-sm" @click="restQueryParams">
                            <i class="layui-icon">&#xe669;</i>重置
                        </button>
                    </div>
                </div>
            </div>
            <div class="layui-row">
                <div class="layui-col-sm3">
                    <div class="layui-inline">
                        <label style="width: 65px">采购员</label>
                        <div class="layui-input-inline">
                            <input type="text" class="layui-input" v-model="queryParams.purchaseUser"/>
                        </div>
                    </div>
                </div>
                <div class="layui-col-sm3">
                    <div class="layui-inline">
                        <label style="width: 65px">订单日期</label>
                        <div class="layui-input-inline">
                            <input type="text" class="layui-input" id="orderDateTime">
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </blockquote>

    <%-- table grid --%>
    <div id="toolbarPO">
        <label class="layui-word-aux">订单列表</label>
        <button type="button" @click="addDeliveryOrder" class="layui-btn layui-btn-sm layui-btn-normal">
            <i class="layui-icon">&#xe654;</i>创建送货单
        </button>
        <button type="button" @click="addRejectedOrder" class="layui-btn layui-btn-sm layui-btn-normal">
            <i class="layui-icon">&#xe654;</i>创建退货单
        </button>
    </div>
    <table id="tableGridPurchaseOrder" lay-filter="tableGridFilterPurchaseOrder"></table>

    <div id="toolbarPODR">
        <label class="layui-word-aux">送/退货单列表</label>
        <button type="button" @click="printReject" class="layui-btn layui-btn-sm layui-btn-normal">
            <i class="layui-icon">&#xe66d;</i>退货单打印
        </button>
    </div>
    <table id="tableGridDROrder" lay-filter="tableGridFilterDROrder"></table>
    <iframe style="visibility:hidden;" id="myIframeReject" name="myIframeReject"
            src="${APP_PATH}/ycl/purchaseIn/PurchaseOrder/toRejectPrint" width=0 height=0></iframe>

    <div id="toolbarPOInOutFlow">
        <label class="layui-word-aux">送/退货单详细列表</label>
        <button type="button" @click="addPOInOut" class="layui-btn layui-btn-sm layui-btn-normal">
            <i class="layui-icon">&#xe654;</i>增加
        </button>
        <button type="button" @click="subPOInOut" class="layui-btn layui-btn-sm layui-btn-normal">
            <i class="layui-icon">&#xe605;</i>提交
        </button>
        <button type="button" @click="delPOInOut" class="layui-btn layui-btn-sm layui-btn-danger">
            <i class="layui-icon">&#xe640;</i>清除
        </button>
        <%-- <button type="button" @click="printInout" class="layui-btn layui-btn-sm layui-btn-normal">
             <i class="layui-icon">&#xe66d;</i>打印
         </button>--%>
        <%--<div class="layui-input-inline">
            <label style="width: 40px">仓库：</label>
            <div class="layui-input-inline">
                <select id="storeSelectPOInOutFlow" lay-filter="storeSelectPOInOutFlow" lay-search="">
                    <option value="">请选择</option>
                </select>
            </div>
        </div>--%>
    </div>
    <div id="divtable">
        <table id="tableGridInOutFlow" lay-filter="tableGridFilterInOutFlow"></table>
    </div>
    <iframe style="visibility:hidden;" id="myIframeInout" name="myIframeInout"
            src="${APP_PATH}/ycl/purchaseIn/PurchaseOrder/toInoutPrint" width=0 height=0></iframe>

</div>

<script src="/wms/static/js/techbloom/LodopFuncs.js" charset="utf-8"></script>
<script>

    const context_path = '${APP_PATH}';
    const table = layui.table,
        layer = layui.layer,
        form = layui.form,
        laydate = layui.laydate;

    let vm = new Vue({
        el: '#yclPurchaseOrderPage',
        data: {
            queryParams: {
                poCode: "",
                supplierName: "",
                materialCode: "",
                purchaseUser: "",
                orderTimeStart: "",
                orderTimeEnd: "",
                poNum: ""
            },
            // 点击订单
            poCode: "",
            poLineNum: "",
            // 点击送退货
            businessCode: "",
            areaCode: "",
            areaName: "",
            storeCode: "",
            storeName: "",
            // 勾选的行物料
            lineItem: {},
            //
            storeSelectList: [],
            shelfCodelist: [] //库位
        },
        watch: {},
        methods: {
            initTableIns() {
                table.render({
                    elem: '#tableGridPurchaseOrder'
                    , url: context_path + '/ycl/purchaseIn/PurchaseOrder/pageView'
                    , page: true
                    , id: "tableGridSetPurchaseOrder"
                    , size: 'sm'
                    , cols: [[
                        {type: 'checkbox'}
                        , {field: 'supplierName', title: '供应商'}
                        , {field: 'purchaseDept', title: '收货组织', width: 150}
                        , {field: 'poCode', title: '订单号', width: 85}
                        , {field: 'poLineNum', title: '行号', width: 55}
                        , {field: 'materialCode', title: '物料编号', width: 130}
                        , {field: 'materialName', title: '物料名称'}
                        , {field: 'primaryUnit', title: '单位', width: 55}
                        , {field: 'quantity', title: '订单数量', width: 80}
                        // , {field: '', title: '紧急状态', width: 85}
                        , {field: 'purchaseUser', title: '采购员', width: 70}
                        , {field: 'orderTime', title: '创建时间', width: 145}
                    ]]
                });
            },
            //第二栏
            initTableIns2() {
                table.render({
                    elem: '#tableGridDROrder'
                    , id: "tableGridSetDROrder"
                    , data: []
                    , page: true
                    , size: 'sm'
                    , cols: [[
                        {type: 'radio'}
                        , {field: 'asnTypeName', title: '单据类型', width: 80}
                        , {field: 'asnNumber', title: '送/退货单号', width: 140}
                        , {field: 'vendorName', title: '供应商', width: 200}
                        , {field: 'areaName', title: '厂区', width: 80}
                        , {field: 'areaCode', hide: true}
                        , {field: 'storeName', title: '仓库', width: 160}
                        , {field: 'storeCode', hide: true}
                        , {field: 'expressNumber', title: '车牌号', width: 90}
                        , {field: 'creationDate', title: '创建时间', width: 95}
                        , {field: 'remark', title: '备注'}
                        , {field: 'asnType', hide: true}
                    ]]
                });
            },
            //第三栏
            initTableIns3() {
                table.render({
                    elem: '#tableGridInOutFlow'
                    , id: "tableGridSetInOutFlow"
                    , data: []
                    , size: 'sm'
                    , cols: [[
                        {type: 'checkbox'}
                        // , {
                        //     field: 'status', title: '状态', width: 70, templet: function (d) {
                        //         if (d.status == '1') {
                        //             return '<span>已上架</span>'
                        //         } else {
                        //             return '<span>未上架</span>'
                        //         }
                        //     }
                        // }
                        , {field: 'tempId', hide: true}
                        , {field: 'businessCode', title: '送/退货单号', width: 125}
                        , {field: 'lotsNum', title: '批次号', width: 95}
                        , {field: 'materialCode', title: '物料编号', width: 95}
                        , {field: 'materialName', title: '物料名称', width: 140}
                        , {field: 'quantity', title: '收/退货数量', width: 95}
                        // , {field: 'locatorCode', title: '库位编码', edit: 'text'}
                        , {field: 'locatorCode', title: '库位', width: 95, templet: (d) => vm.renderSelectOptions(d)}
                        , {field: 'deliverQuantity', title: '出/入库数量', edit: 'text', width: 90}
                        , {field: 'updownQuantity', hide: true}
                        , {field: 'primaryUnit', title: '单位', width: 60}
                        , {field: 'lotsNumYd', title: '标签号', width: 260}
                    ]]
                });
            },
            initStoreList() {
                $.post(context_path + '/warehouselist/getYclWarehouseByFactory', {
                    factoryCode: ''
                }, function (res) {
                    let html = '';
                    let list = res.data;
                    for (let i = 0; i < list.length; i++) {
                        html += '<option value=' + list[i].id + '>' + list[i].text + '</option>';
                    }
                    $("#storeSelectPOInOutFlow").empty();
                    $("#storeSelectPOInOutFlow").append('<option value="">请选择</option>');
                    $("#storeSelectPOInOutFlow").append(html);
                    form.render('select', 'storeSelectPOInOutFlow');
                })
            },
            queryPageView() {
                table.reload('tableGridSetPurchaseOrder', {
                    where: vm.queryParams
                    , page: {
                        curr: 1
                    }
                });
            },
            restQueryParams() {
                vm.queryParams = {
                    poCode: "",
                    supplierName: "",
                    materialCode: "",
                    purchaseUser: "",
                    orderTimeStart: "",
                    orderTimeEnd: ""
                }
                $("#orderDateTime").val('');
                table.reload('tableGridSetPurchaseOrder', {
                    where: vm.queryParams
                    , page: {
                        curr: 1
                    }
                });
            },
            // 创建送货单
            addDeliveryOrder() {
                const checkStatusData = table.checkStatus('tableGridSetPurchaseOrder').data
                let purchaseOrderIds = checkStatusData.map(item => item.poLineId).toString()
                if (checkStatusData.length === 0) {
                    layer.msg('请选择订单', {icon: 2});
                    return
                }
                if (checkStatusData.some(item => item.supplierId != checkStatusData[0].supplierId)) {
                    layer.msg('请选择相同供应商', {icon: 2});
                    return
                }
                if (checkStatusData.some(item => item.purchaseOrganId != checkStatusData[0].purchaseOrganId)) {
                    layer.msg('请选择相同收货方', {icon: 2});
                    return
                }
                layer.open({
                    title: '新增'
                    , type: 2
                    , area: ['1200px', '600px'] //宽高
                    , maxmin: true,
                    content: context_path + '/ycl/purchaseIn/PurchaseOrder/toDeliveryOrderEdit?purchaseOrderIds=' + purchaseOrderIds
                });
            },
            addRejectedOrder() {
                const checkStatusData = table.checkStatus('tableGridSetPurchaseOrder').data
                // let purchaseOrderIds = checkStatusData.map(item => item.poCode + '_' + item.poLineNum).toString()
                let purchaseOrderIds = checkStatusData.map(item => item.poLineId).toString()
                if (checkStatusData.length === 0) {
                    layer.msg('请选择订单', {icon: 2});
                    return
                }
                if (checkStatusData.some(item => item.supplierId != checkStatusData[0].supplierId)) {
                    layer.msg('请选择相同供应商', {icon: 2});
                    return
                }
                console.log(checkStatusData[0])
                let supplierName = checkStatusData[0].supplierName
                let purchaseOrgan = checkStatusData[0].purchaseOrgan
                let purchaseUser = checkStatusData[0].purchaseUser

                layer.open({
                    title: '新增'
                    , type: 2
                    , area: ['1200px', '600px'] //宽高
                    , maxmin: true
                    ,
                    content: context_path + '/ycl/purchaseIn/PurchaseOrder/toRejectedOrderEdit?purchaseOrderIds=' + purchaseOrderIds
                        + '&supplierName=' + supplierName
                        + '&purchaseOrgan=' + purchaseOrgan
                        + '&purchaseUser=' + purchaseUser
                });
            },

            // 增加上架 增行
            addPOInOut() {

                const checkStatusData = table.checkStatus('tableGridSetInOutFlow').data
                if (checkStatusData.length != 1) {
                    layer.msg("请选择一种物料进行操作", {icon: 2});
                    return
                }
                // 出入库流水标准
                let newRow = {
                    tempId: new Date().valueOf(),
                    businessCode: checkStatusData[0].businessCode,
                    lotsNum: checkStatusData[0].lotsNum,
                    materialCode: checkStatusData[0].materialCode,
                    materialName: checkStatusData[0].materialName,
                    quantity: checkStatusData[0].quantity,
                    locatorCode: '',
                    updownQuantity: '',
                    deliverQuantity: '',
                    primaryUnit: checkStatusData[0].primaryUnit,
                    areaCode: vm.areaCode,
                    areaName: vm.areaName,
                    storeCode: vm.storeCode,
                    storeName: vm.storeName
                }

                let oldData = table.cache['tableGridSetInOutFlow'];
                oldData.push(newRow);
                console.log(oldData);
                table.reload('tableGridSetInOutFlow', {
                    data: oldData
                })
            },
            subPOInOut() {
                let subData = table.cache['tableGridSetInOutFlow'];
                console.log(subData)

                if (subData.length == 0) {
                    layer.msg("提交数据不能为空", {icon: 0});
                    return
                }
                for (let i = 0; i < subData.length; i++) {
                    let item = subData[i]

                    if (item.status == '1') {
                        layer.msg("物料已操作，无法重复操作", {icon: 0});
                        return;
                    }

                    // 送货单
                    if (item.businessCode.substring(3, 0) == 'SHD') {
                        if (item.locatorCode == null) {
                            layer.msg("编辑数据不能为空", {icon: 0});
                            return;
                        }
                    }

                    if (item.locatorCode == '' || item.deliverQuantity == '' || item.deliverQuantity == null) {
                        layer.msg("编辑数据不能为空", {icon: 0});
                        return;
                    }

                    if (typeof item.deliverQuantity != 'number' && isNaN(item.deliverQuantity)) {
                        layer.msg('请输入有效数字', {icon: 2});
                        return
                    }

                    if (parseFloat(item.deliverQuantity) <= 0) {
                        layer.msg("出入库数量不能小于等于0", {icon: 0});
                        return;
                    }

                    if (parseFloat(item.deliverQuantity) > parseFloat(item.quantity)) {
                        layer.msg("出入库数量不能大于送退货数量", {icon: 0});
                        return;
                    }

                    let c = subData.filter(a => a.lotsNum === item.lotsNum && a.materialCode === item.materialCode)
                        .reduce((sum, b) => sum + (b.deliverQuantity) * 1, 0)

                    let d = subData.filter(a => a.lotsNum === item.lotsNum && a.materialCode === item.materialCode)
                        .reduce((sum, b) => sum + (b.quantity) * 1, 0)

                    if (item.quantity < c) {
                        layer.msg("同一种物料的出入库数量总和不能大于该物料的收退货数量", {icon: 0});
                        return;
                    }

                    item.updownQuantity = item.deliverQuantity
                    item.areaCode = vm.areaCode
                    item.areaName = vm.areaName
                    item.storeCode = vm.storeCode
                    item.storeName = vm.storeName
                    // item.inoutType = '1'
                }

                layer.load(2, {time: 3*1000});

                $.ajax({
                    type: 'POST',
                    url: context_path + "/ycl/ordermanage/asn/editAsnLineBatch",
                    contentType: "application/json",
                    async: false,
                    dataType: "json",
                    data: JSON.stringify(subData),
                    success: function (res) {
                        layer.msg(res.msg);
                        table.reload('tableGridSetInOutFlow');
                    }
                })
            },
            delPOInOut() {
                const checkStatusData = table.checkStatus('tableGridSetInOutFlow').data
                if (checkStatusData.length === 0) {
                    layer.msg('至少选择一条数据', {icon: 2});
                    return
                }
                layer.confirm('确定删除？', {icon: 3, title: '提示信息'}, function (index) {
                    let oldData = table.cache['tableGridSetInOutFlow'];

                    for (let i = 0; i < checkStatusData.length; i++) {
                        for (let j = 0; j < oldData.length; j++) {
                            if (checkStatusData[i].tempId === oldData[j].tempId) {
                                oldData.splice(j, 1);
                            }
                        }
                    }
                    let ids = checkStatusData.map(item => {
                        console.log(typeof item.id != 'undefined')
                        if (typeof item.id != 'undefined') {
                            return item.id
                        }
                    })
                    let newArr = ids.filter((item, index, arr) => {
                        return typeof item != 'undefined'
                    });
                    if (newArr.length > 0) {
                        $.get(context_path + '/ycl/operation/yclInOutFlow/delete', {ids: newArr.toString()}, function (res) {
                            layer.msg(res.msg);
                        })
                    } else {
                        layer.msg("操作成功！");
                    }
                    table.reload('tableGridSetInOutFlow', {
                        data: oldData
                    });
                })
            },
            printInout() {
                let oldData = table.cache['tableGridSetInOutFlow'];
                var frm = document.getElementById('myIframeInout');
                frm.src = '/wms/ycl/insidewarehouse/transferOrder/toPrint?tcode=' + selectData[0].tranCode;
                $(frm).load(function () {
                    LODOP = getLodop();
                    var strHtml = frm.contentWindow.document.documentElement.innerHTML;
                    LODOP.ADD_PRINT_HTM(0, 0, "100%", "100%", strHtml);
                    LODOP.PREVIEW();
                });
            },
            printReject() {
                let rowData = table.checkStatus('tableGridSetDROrder').data

                if (rowData.length === 0) {
                    layer.msg('至少选择一条数据', {icon: 2});
                    return
                }

                if (rowData[0].asnType != '3') {
                    layer.msg('请选择退货单打印', {icon: 2});
                    return
                }
                console.log(context_path)
                let frm = document.getElementById('myIframeReject');
                frm.src = context_path + '/ycl/purchaseIn/PurchaseOrder/toRejectPrint?asnHeaderId=' + rowData[0].asnHeaderId;
                $(frm).load(function () {
                    LODOP = getLodop();
                    let strHtml = frm.contentWindow.document.documentElement.innerHTML;
                    LODOP.ADD_PRINT_HTM(0, 0, "100%", "100%", strHtml);
                    LODOP.PREVIEW();
                });
            },
            renderSelectOptions(e) {
                let html = [];
                html.push('<div class="layui-form" lay-filter="shelfCode">');
                html.push('<select name="shelfCode" id="shelfCode" data-value="' + e.tempId + '" lay-filter="shelfCode" lay-search="">');
                html.push('<option value="">请选择</option>');
                this.shelfCodelist.forEach(m => {
                    html.push('<option value="');
                    html.push(m.code);
                    html.push('"');
                    if (m.code == e.locatorCode) {
                        html.push(' selected="selected"');
                    }
                    html.push('>');
                    html.push(m.codename);
                    html.push('</option>');
                })
                html.push('</select></div>');
                return html.join('');
            }
        },
        created() {
        },
        mounted() {
        }

    })

    // 点击订单物料 查询主表
    table.on('row(tableGridFilterPurchaseOrder)', function (obj) {
        const data = obj.data;
        console.log("订单物料", data)
        vm.poCode = data.poCode
        vm.poLineNum = data.poLineNum
        $.get(context_path + '/ycl/ordermanage/asn/listViewHeaderBy', {
            // poLineId: data.poLineId
            poCode: data.poCode,
            poLineNum: data.poLineNum
        }, function (res) {
            table.reload('tableGridSetDROrder', {
                data: res.data
            });
        })
        obj.tr.addClass('layui-table-click').siblings().removeClass('layui-table-click');
        table.reload('tableGridSetInOutFlow', {
            data: []
        });
    });

    // 点击送退货单 查询子表
    table.on('row(tableGridFilterDROrder)', function (obj) {
        obj.tr.find('i[class="layui-anim layui-icon"]').trigger("click");
        const data = obj.data;
        console.log("送退货单", data)
        vm.businessCode = data.asnNumber
        vm.areaCode = data.areaCode
        vm.areaName = data.areaName
        vm.storeCode = data.storeCode
        vm.storeName = data.storeName

        $.get(context_path + '/goods/getShelfByFactWareCode.do', {
            warehouseCode: data.storeCode,
            entityId: data.areaCode,
            queryString: '',
            pageSize: 999,
            pageNo: 1
        }, function (res) {
            vm.shelfCodelist = res.result
        })

        $.get(context_path + '/ycl/ordermanage/asn/listViewAsnSelect', {
            asnHeaderIds: data.asnHeaderId,
            asnNumber: data.asnNumber,
        }, function (res) {
            let lines = res.data
            for (let i = 0; i < lines.length; i++) {
                if (lines[i].isInOutData === '0') {
                    lines[i].tempId = new Date().valueOf() + i
                    lines[i].businessCode = vm.businessCode
                    lines[i].quantity = lines[i].shipQuantity // 发运数量
                    lines[i].deliverQuantity = lines[i].shipQuantity // 收货
                    lines[i].updownQuantity = ''
                }
            }
            table.reload('tableGridSetInOutFlow', {
                data: lines
            });
        })
        obj.tr.addClass('layui-table-click').siblings().removeClass('layui-table-click');
    });

    function tableRender() {
        $.get(context_path + '/ycl/ordermanage/asn/listViewHeaderBy', {
            poCode: vm.poCode,
            poLineNum: vm.poLineNum
        }, function (res) {
            table.reload('tableGridSetDROrder', {
                data: res.data
            });
        })
    }

    //监听select
    form.on('select(shelfCode)', function (data) {
        var elem = data.othis.parents('tr');
        var id = elem.first().find('td').eq(1).text();
        let val = data.value
        this.tbData = table.cache['tableGridSetInOutFlow'];
        this.tbData.forEach(n => {
            if (n.tempId == id) {
                n.locatorCode = data.value;
            }
        })
        table.reload({
            data: this.tbData
        });
    });

    // init
    ;!function () {

        laydate.render({
            elem: '#orderDateTime'
            , type: 'date'
            , range: '~'
            , done: function (value, date, endDate) {
                console.log(value)
                if (typeof value != 'undefined' && value != '' && value != null) {
                    let dateTime = value.split('~')
                    vm.queryParams.orderTimeStart = dateTime[0] + ' 00:00:00'
                    vm.queryParams.orderTimeEnd = dateTime[1] + ' 23:59:59'
                } else {
                    vm.queryParams.orderTimeStart = null
                    vm.queryParams.orderTimeEnd = null
                }
            }
        });

        vm.initTableIns()
        vm.initTableIns2()
        vm.initTableIns3()
        // vm.initStoreList()

    }();
</script>